﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Skyhook.Core;
using Microsoft.Xna.Framework;
using Skyhook.AI.States;
using Skyhook.AI.States.MovingEntity;

namespace Skyhook.AI.MovingObjects
{
    public class MovingEntity
    {
        IObjectController ObjectController = null;
        float MoveSpeed = 0.0f;

        IdleState Idle = null;
        MovingState Moving = null;

        State CurrentState = null;

        public MovingEntity(IObjectController controller, float speed)
        {
            MoveSpeed = speed;
            ObjectController = controller;

            CreateAndInitializeStates();

            IsFinished = false;
        }

        public bool IsFinished
        {
            get;
            private set;
        }

        public void MoveToPoint(int x, int y)
        {
            Moving.SetDestination(x, y);

            CurrentState.NextState = Moving;
            
            CurrentState.Stop();
            UpdateState();

            IsFinished = false;
        }

        public void Update(float elapsedticks)
        {
            IsFinished = false;
            CurrentState.Update(elapsedticks);
            UpdateState();
        }

        void UpdateState()
        {
            if (CurrentState.IsFinished)
            {
                ChangeState();
                SetDefaultNextStates();
            }
        }

        void CreateAndInitializeStates()
        {
            Idle = new IdleState();

            Moving = new MovingState(ObjectController);
            Moving.SetSpeed(MoveSpeed);

            CurrentState = Idle;

            SetDefaultNextStates();
        }

        void ChangeState()
        {
            if (CurrentState.NextState == Idle)
            {
                IsFinished = true;
            }

            CurrentState = CurrentState.NextState;
            CurrentState.Start();
        }

        void SetDefaultNextStates()
        {
            Idle.NextState = State.None;
            Moving.NextState = Idle;
        }
    }
}
